package ru.gerunn.silent.message;

import java.util.concurrent.Callable;

import ru.gerunn.silent.exception.SilentMessageQueueException;
import ru.gerunn.silent.exception.SilentWriteMessageException;
import ru.gerunn.silent.server.Server;
import ru.gerunn.silent.server.Session;

public class MessageQueueCallable implements Callable<Object> {

	private final Server server;
	private final MessageQueue messageQueue;

	public MessageQueueCallable(Server server, MessageQueue messageQueue) {
		this.server = server;
		this.messageQueue = messageQueue;
	}
	
	public Object call() throws SilentMessageQueueException {
		try {
			Message message;
			while ((message = messageQueue.get()) != null) {
				for (Session session : this.server.getSessions().values()) {
					try {
						session.write(message);
					} catch (SilentWriteMessageException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		} catch (InterruptedException e) {
			throw new SilentMessageQueueException("error while getting from message queue", e.getCause());
		}
		return null;
	}

}
